package net.xdclass.exception;


import lombok.extern.slf4j.Slf4j;
import net.xdclass.utils.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


@ControllerAdvice //需要在对应的方法中加ResponseBody
//@RestControllerAdvice //直接返回对应的json数据，不用加ResponseBody
@Slf4j
public class CustomExceptionHandler {

    @ExceptionHandler(value = Exception.class) //捕获哪个异常，设置为捕获基类的异常
    @ResponseBody //如果使用了RestControllerAdvice注解那么就不用加ResponseBody
    public JsonData handler(Exception e){

        if(e instanceof  BizException){  //抓取并判断是否是自定义异常
            BizException bizException = (BizException) e;
            log.error("[业务异常]{}",e);
            return JsonData.buildCodeAndMsg(bizException.getCode(),bizException.getMessage());
        }else{
            log.error("[系统异常]{}",e);
            return JsonData.buildError("系统异常");
        }
    }
}
